package com.example.scheduled;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.util.Base64Utils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: m-mall-user
 * @description: pdf转图片
 * @author: Mr.Wang
 * @create: 2019-11-30 17:56
 **/
public class PdfUtil {

    /**
     * 转换全部的pdf
     * * @param fileAddress 文件地址
     * * @param filename PDF文件名
     * * @param type 图片类型
     */
    public static List<String> pdf2png(InputStream file) throws IOException {
//    public static List<String> pdf2png(File file) throws IOException {
        PDDocument doc = new PDDocument();
        List<String> result = new ArrayList<>();
        // 将pdf装图片 并且自定义图片得格式大小
        try {
            //加载 pdf 文档
            doc = PDDocument.load(file);
            //PDDocument doc = PDDocument.load(steam);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = 0; i < pageCount; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI
                //BufferedImage srcImage = resize(image, 240, 240);//产生缩略图
                //ImageIO.write(image, type, new File(fileAddress + "\\" + filename + "_" + (i + 1) + "." + type));
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                ImageIO.write(image, "jpg", outputStream);
                String base64Img = Base64Utils.encodeToString(outputStream.toByteArray());
                base64Img = "data:image/jpg;base64," + base64Img;
                result.add(base64Img);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            doc.close();
        }

        return result;
    }
}
